package cn.sirun.com.fca.map.view.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.storage.TXSharedPreferencesUtils;
import com.tencent.cloud.uikit.widget.edittext.LineEditText;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.param.Geo2AddressParam;
import com.tencent.lbssearch.object.result.Geo2AddressResultObject;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdate;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TextureMapView;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;


import cn.sirun.com.fca.map.R;
import cn.sirun.com.fca.map.constant.MapActivityConst;
import cn.sirun.com.fca.map.model.repose.MapCarLocation;
import cn.sirun.com.fca.map.model.repose.MapCollectedResponse;
import cn.sirun.com.fca.map.model.repose.MapHomeCompanyResponse;
import cn.sirun.com.fca.map.presenter.IMapPresenter;
import cn.sirun.com.fca.map.presenter.impl.MapPresenter;
import cn.sirun.com.fca.map.view.IMapCollectedView;


public class MapFlowView extends MapBaseLoadingFlowView<IMapPresenter>implements IMapCollectedView {

    private TextureMapView mMapView;
    private TextView mSearchET;
    private TencentMap tencentMap;
    private LatLng carLatLng;
    private LatLng getmLatLng;
    private Marker carMarker;
    private Marker manMarker;
    private ImageView ivcarcenter;
    private LocationManager locationManager;
    private String locationProvider;
    private CameraUpdate cameraSigma;
    private StringBuilder sb;
    private String din;


    public MapFlowView(Activity activity) {
        super(activity);
    }

    public MapFlowView(Activity activity, IContentViewContainer container) {
        super(activity, container);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.map_fragment, null, false);
        setContentView(view);
        mMapView = view.findViewById(R.id.map);
        mSearchET = view.findViewById(R.id.map_search);

        final Activity activity = getActivity();
        mSearchET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent inent = Router.fromPath(MapActivityConst.Path.MAP_SEARCH);
                ActivityUtils.startActivity(activity, inent);
            }
        });

        tencentMap = mMapView.getMap();

        din=TXSharedPreferencesUtils.getValue("car_activate_info");
//
        if(!TextUtils.isEmpty(din)){
            getPresenter().getLastLocation(din);
        }else {
            getPresenter().updateLocation("");
        }

        carLatLng = new LatLng(39.90, 116.38);
        //汽车位置，人的位置
        addMarkers();
        //地图中心设置
        cameraSigma = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                new LatLng(39.90, 116.38), //新的中心点坐标
                9,  //新的缩放级别
                0, //俯仰角 0~45° (垂直地图时为0)
                0)); //偏航角 0~360° (正北方为0)
        tencentMap.moveCamera(cameraSigma);
        ivcarcenter = view.findViewById(R.id.iv_car_to_center);
        ivcarcenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //移动地图
                tencentMap.moveCamera(cameraSigma);
                if(!TextUtils.isEmpty(din)){
                    getPresenter().updateLocation(din);
                }else {
                    getPresenter().updateLocation("");
                }
            }
        });
        //点击marker
        tencentMap.setOnMarkerClickListener(new TencentMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if(marker.equals(manMarker)){
                    Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
                    intent.putExtra("set","send");
                    intent.putExtra("addresslat",manMarker.getPosition().latitude+"");
                    intent.putExtra("addresslng",manMarker.getPosition().longitude+"");
                    intent.putExtra("title","man");
                    intent.putExtra("address","man");
                    ActivityUtils.startActivity(activity, intent);
                }else if(marker.equals(carMarker)){
//                    marker.showInfoWindow();
                    Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
                    intent.putExtra("set","send");
                    intent.putExtra("addresslat",carMarker.getPosition().latitude+"");
                    intent.putExtra("addresslng",carMarker.getPosition().longitude+"");
                    intent.putExtra("title","man");
                    intent.putExtra("address","man");
                    ActivityUtils.startActivity(activity, intent);
                }
                return true;
            }
        });

    }


    private void addMarkers() {
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.car_marker);
        carMarker = tencentMap.addMarker(new MarkerOptions()
                .icon(bitmap)
                .position(carLatLng)
                .draggable(true));

        //显示信息窗
        TencentMap.InfoWindowAdapter infoWindowAdapter = new TencentMap.InfoWindowAdapter() {
            TextView tvTitle;
            //返回View为信息窗自定义样式，返回null时为默认信息窗样式
            @Override
            public View getInfoWindow(final Marker arg0) {
                if (arg0.equals(carMarker)) {
                    RelativeLayout custInfowindow = (RelativeLayout) View.inflate(
                            getActivity(), R.layout.marker_infowindow_layout, null);
                    tvTitle = (TextView) custInfowindow.findViewById(R.id.tv_title);
                    tvTitle.setText(carMarker.getTitle());
                    return custInfowindow;
                }
                return null;
            }
            //返回View为信息窗内容自定义样式，返回null时为默认信息窗样式
            @Override
            public View getInfoContents(Marker arg0) {
                return null;
            }
        };
        //设置信息窗适配器
        tencentMap.setInfoWindowAdapter(infoWindowAdapter);

        locationManager = (LocationManager) getActivity().getSystemService(getContext()
                .LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度，如果设置为高精度，依然获取不了location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);//允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
        locationProvider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission
                .ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission
                .ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            //不为空,显示地理位置经纬度
            showLocation(location);
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
    }

    /**
     * 逆地理编码
     */
    protected void reGeocoder(String str) {

        str = "39.90,116.38";
        com.tencent.lbssearch.object.Location location = str2Coordinate(getContext(), str);
        if (location == null) {
            return ;
        }
        TencentSearch tencentSearch = new TencentSearch(getContext());
        //还可以传入其他坐标系的坐标，不过需要用coord_type()指明所用类型
        //这里设置返回周边poi列表，可以在一定程度上满足用户获取指定坐标周边poi的需求
        Geo2AddressParam geo2AddressParam = new Geo2AddressParam().
                location(location).get_poi(true);
        tencentSearch.geo2address(geo2AddressParam, new HttpResponseListener() {

            @Override
            public void onSuccess(int arg0, BaseObject arg1) {
                // TODO Auto-generated method stub
                if (arg1 == null) {
                    return;
                }
                Geo2AddressResultObject obj = (Geo2AddressResultObject)arg1;
                sb = new StringBuilder();
                sb.append(obj.result.address);
                carMarker.setTitle(sb.toString());
            }

            @Override
            public void onFailure(int arg0, String arg1, Throwable arg2) {
                // TODO Auto-generated method stub
//                printResult(arg1);
            }
        });

    }

    /**
     * 由字符串获取坐标
     * @param context
     * @param str
     * @return
     */
    public static com.tencent.lbssearch.object.Location str2Coordinate(Context context, String str) {
        if (!str.contains(",")) {
            Toast.makeText(context, "经纬度用\",\"分割", Toast.LENGTH_SHORT).show();
            return null;
        }
        String[] strs = str.split(",");
        float lat = 0;
        float lng = 0;
        try {
            lat = Float.parseFloat(strs[0]);
            lng = Float.parseFloat(strs[1]);
        } catch (NumberFormatException e) {
            Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
            return null;
        }
        return new com.tencent.lbssearch.object.Location(lat, lng);
    }

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }

        @Override
        public void onProviderEnabled(String provider) {
//            Log.d(TAG, "onProviderEnabled: " + provider + ".." + Thread.currentThread().getName
// ());
        }

        @Override
        public void onProviderDisabled(String provider) {
//            Log.d(TAG, "onProviderDisabled: " + provider + ".." + Thread.currentThread()
// .getName());
        }

        @Override
        public void onLocationChanged(Location location) {
            //如果位置发生变化,重新显示
            showLocation(location);
        }
    };

    private void showLocation(Location location) {
        //构建Marker图标
        if(manMarker!=null){
            manMarker.remove();
        }
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.man_marker);
        getmLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        manMarker = tencentMap.addMarker(new MarkerOptions()
                .icon(bitmap)
                .position(getmLatLng)
                .draggable(true));
//        Log.d(TAG,"定位成功------->"+"location------>经度为：" + location.getLatitude() + "\n纬度为" +
// location.getLongitude());
    }

    @Override
    public void onStart() {
        super.onStart();
        mMapView.onStart();
        addMarkers();
        if(!TextUtils.isEmpty(din)){
            getPresenter().getLastLocation(din);
        }else {
            getPresenter().getLastLocation("");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mMapView.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    protected IMapPresenter createPresenter() {
        return new MapPresenter();
    }

    @Override
    public void getMapCollected(BaseResponse<MapCollectedResponse> response) {

    }

    @Override
    public void addMapCollected(BaseResponse<BaseResponse> response) {

    }

    @Override
    public void deleteMapCollected(BaseResponse<BaseResponse> response) {

    }

    @Override
    public void mapHomeCompany(BaseResponse<MapHomeCompanyResponse> response) {

    }

    @Override
    public void mapSendToCar(BaseResponse<MapHomeCompanyResponse> response) {

    }

    @Override
    public void getLastLocation(BaseResponse<MapCarLocation> response) {

    }

    @Override
    public void updateLocation(BaseResponse<MapCarLocation> response) {

    }
}
